package com.generic.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {

	public static boolean sendMail(final String username, final String password,
			String port, String to, String cc, String bcc, String from,
			String mailhost, String send_subject, String send_content,
			String AttPath, String[] filename, String[] mfname, boolean sendfile)
			throws AddressException, MessagingException {

		String msgText1 = send_content;
		String subject = send_subject;
		boolean redata = false;
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

		Properties props = System.getProperties();
    	
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", mailhost);
		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);		
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.socketFactory.port", port);
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.put("mail.debug", "true");
    	
//		props.put("mail.smtp.localhost", mailhost);

//		Session session = Session.getInstance(props);
    	
		Session session = Session.getDefaultInstance(props,
		new javax.mail.Authenticator() 
		{
			protected PasswordAuthentication getPasswordAuthentication()
			{ return new PasswordAuthentication(username,password);	}
		});
		session.setDebug(true);

		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(from));

		int ix = 0;

		if (to.trim().length() != 0) {
			String[] ato = StringToken(to, ";");
			InternetAddress[] address = new InternetAddress[ato.length];

			for (ix = 0; ix < ato.length; ix++) {
				String[] tokenA = StringToken(ato[ix], "<");

				if (tokenA.length > 1) {
					ato[ix] = tokenA[1];

					String[] tokenB = StringToken(ato[ix], ">");
					ato[ix] = tokenB[0];
				}

				address[ix] = new InternetAddress(ato[ix]);
			}

			msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
		}

		if (cc.trim().length() != 0) {
			String[] cto = StringToken(cc, ";");
			InternetAddress[] ccaddress = new InternetAddress[cto.length];

			for (ix = 0; ix < cto.length; ix++) {
				String[] tokenA = StringToken(cto[ix], "<");

				if (tokenA.length > 1) {
					cto[ix] = tokenA[1];

					String[] tokenB = StringToken(cto[ix], ">");
					cto[ix] = tokenB[0];
				}

				ccaddress[ix] = new InternetAddress(cto[ix]);
			}

			msg.setRecipients(javax.mail.Message.RecipientType.CC, ccaddress);
		}

		if (bcc.trim().length() != 0) {
			String[] bto = StringToken(bcc, ";");
			InternetAddress[] bccaddress = new InternetAddress[bto.length];

			for (ix = 0; ix < bto.length; ix++) {
				String[] tokenA = StringToken(bto[ix], "<");

				if (tokenA.length > 1) {
					bto[ix] = tokenA[1];

					String[] tokenB = StringToken(bto[ix], ">");
					bto[ix] = tokenB[0];
				}

				bccaddress[ix] = new InternetAddress(bto[ix]);
			}

			msg.setRecipients(javax.mail.Message.RecipientType.BCC, bccaddress);
		}

		// Set email Subject
		msg.setSubject(subject, "UTF-8");
		
		// create and fill the first message part
		MimeBodyPart mbp1 = new MimeBodyPart();
		
		// mbp1.setText(msgText1);
		mbp1.setContent(msgText1, "text/html; charset=UTF-8");

		Multipart mp = new MimeMultipart();
		
		if (sendfile) {
			MimeBodyPart[] mbp2 = new MimeBodyPart[filename.length];
			FileDataSource[] fds = new FileDataSource[filename.length];

			for (int i = 0; i < filename.length; i++) {
				mbp2[i] = new MimeBodyPart();

				// fds[i] = new
				// FileDataSource(AttPath+toUni.toUni(filename[i]));
				fds[i] = new FileDataSource(AttPath + toUni(filename[i]));
				mbp2[i].setDataHandler(new DataHandler(fds[i]));
				mbp2[i].setFileName(mfname[i]);
				mp.addBodyPart(mbp2[i]);
			}
		}

		mp.addBodyPart(mbp1);
		msg.setContent(mp);
		msg.setSentDate(new Date()); // set the Date: header
		
		Transport transport = session.getTransport("smtp");
		transport.connect(mailhost, username, password);
		transport.sendMessage(msg, msg.getAllRecipients());
//		Transport.send(msg);
		
		redata = true;

		return redata;
	}

	public static String[] StringToken(String str1, String str2) {
		boolean isR = false;
		boolean isC = false;
		int count1 = 0;
		int count2 = 0;
		int count3 = 0;
		int count4 = 0;
		String str3 = "";
		String str4 = "";
		Vector<String> vect1 = new Vector<String>();
		count2 = str2.length();

		while (true) {
			try {
				char ch1 = str1.charAt(count1);
				isC = false;

				if (ch1 == str2.charAt(0)) {
					isC = true;
					isR = true;
					count1++;
					count4 = count1;
					str4 = "" + ch1;

					for (count3 = 1; count3 < count2; count3++) {
						ch1 = str1.charAt(count1);
						str4 += ch1;
						count1++;

						if (ch1 != str2.charAt(count3)) {
							isR = false;

							break;
						}
					}

					if (isR) {
						str4 = "";
						vect1.addElement(str3);
						str3 = "";
						count1--;
					} else {
						str3 += str4;
						count1 = count4;
					}
				} else {
					str3 += ch1;
				}
			} catch (StringIndexOutOfBoundsException e) {
				if (!isC) {
					vect1.addElement(str3);
				}

				str3 = "";

				break;
			}

			count1++;
		}

		String[] str5 = new String[vect1.size()];
		count1 = 0;

		while (true) {
			try {
				str5[count1] = (String) vect1.elementAt(count1);
			} catch (ArrayIndexOutOfBoundsException e) {
				break;
			}

			count1++;
		}

		return str5;
	}

	public static String toBig5(String str_1) {
		try {
			String str_2 = "";
			str_2 = new String(str_1.getBytes(), "Big5");

			return str_2;
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}

	public static String toUni(String s1) {
		// to do: code goes here.
		int l = 0;
		byte[] b = new byte[s1.length()];
		l = 0;

		while (true) {
			try {
				b[l] = (byte) s1.charAt(l);
			} catch (ArrayIndexOutOfBoundsException e1) {
				break;
			} catch (StringIndexOutOfBoundsException e2) {
				break;
			}

			l++;
		}

		s1 = new String(b);

		return s1;
	}

	public static String b2u(String s) {
		int i = 0;
		byte[] abyte0 = new byte[s.length()];
		i = 0;

		do {
			try {
				abyte0[i] = (byte) s.charAt(i);
			} catch (ArrayIndexOutOfBoundsException arrayindexoutofboundsexception) {
				break;
			} catch (StringIndexOutOfBoundsException stringindexoutofboundsexception) {
				break;
			}

			i++;
		} while (true);

		s = new String(abyte0);
		i = 0;

		String s1 = "";

		do {
			try {
				long l = 0L;
				l = s.charAt(i);
				s1 = s1 + "&#x" + Long.toHexString(l).toUpperCase() + ";";
			} catch (ArrayIndexOutOfBoundsException arrayindexoutofboundsexception1) {
				break;
			} catch (StringIndexOutOfBoundsException stringindexoutofboundsexception1) {
				break;
			}

			i++;
		} while (true);

		return s1;
	}
}